import { defineConfig } from "vite";
import vue from "@vitejs/plugin-vue";
import { resolve } from "path";

// https://vite.dev/config/
export default defineConfig(({ mode }) => ({
  plugins: [vue()],

  // 配置路径别名
  resolve: {
    alias: {
      '@': resolve(__dirname, 'src')
    }
  },

  // Vite options tailored for Tauri development and only applied in `tauri dev` or `tauri build`
  //
  // 1. prevent Vite from obscuring rust errors
  clearScreen: false,
  // 2. tauri expects a fixed port, fail if that port is not available
  server: {
    port: 3000,
    strictPort: true,
    watch: {
      // 3. tell Vite to ignore watching `src-tauri`
      ignored: ["**/src-tauri/**"],
    }
  },
  
  // 依赖预构建优化
  optimizeDeps: {
    include: ['tesseract.js', 'naive-ui', 'echarts', 'vue-echarts'],
    exclude: ['@tauri-apps/api', '@tauri-apps/plugin-fs']
  },
  
  build: {
    rollupOptions: {
      output: {
        manualChunks: {
          tesseract: ['tesseract.js'],
          naive: ['naive-ui'],
          echarts: ['echarts', 'vue-echarts'],
          vue: ['vue', 'vue-router', 'pinia']
        }
      }
    },
    // 启用代码分割优化
    chunkSizeWarningLimit: 1000,
    // 启用CSS代码分割
    cssCodeSplit: true,
    // 启用源码映射（生产环境可关闭）
    sourcemap: mode === 'development',
    // 生产环境优化
    minify: mode === 'production' ? 'terser' : false,
    // 启用gzip压缩
    reportCompressedSize: true,
    // 优化依赖预构建
    target: 'esnext'
  },
  
  // 配置worker文件
  worker: {
    format: 'es'
  },
  
  // 配置静态文件服务
  publicDir: 'public',
  
  // 生产环境特定配置
  ...(mode === 'production' && {
    build: {
      // 启用更激进的压缩
      minify: 'terser',
      terserOptions: {
        compress: {
          drop_console: true,
          drop_debugger: true,
          pure_funcs: ['console.log', 'console.info', 'console.debug']
        }
      }
    }
  })
}));
